package org.homly.pc.action.order;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.homly.model.Config;
import org.homly.service.ProductService;
import org.homly.sql.SQLTool;
import org.homly.tool.OpCookies;
import org.homly.tool.StringTool;

/**
 * 保存配置和订单
 * @author Dragon
 * @date 2012-11-14
 *
 */
public class SaveTrolleyAction extends Action {

	@SuppressWarnings("unchecked")
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		List<HashMap<String, String>> trolley = null;
		String productIdsS = "";
		double totalPrice = (double) 0;
		int trolleySize = 0;

		try {
			JSONObject[] trolleyJSONObjectArray = getTrolley(request);

			if (trolleyJSONObjectArray != null && trolleyJSONObjectArray.length > 0) {
				productIdsS = getProductIdsS(trolleyJSONObjectArray);
				HashMap para = new HashMap();
				para.put("productIds", productIdsS);
				para.put("status", (short) 1);
				trolley = ProductService.getProducts(para);
			}

			if (trolley != null && trolley.size() > 0) {
				trolleySize = trolley.size();
				for (int i = trolleySize - 1; i >= 0; i --) {
					HashMap<String, String> product = trolley.get(i);
					ProductService ps = new ProductService();
					HashMap para = new HashMap();
					para.put("id", Integer.valueOf(product.get("config_id")));
					HashMap<String, String> config = ps.getConfig(para);
					product.put("config_name", config.get("config_name"));
					String numS = (String) request.getParameter("num_" + product.get("product_id"));
					product.put("num", numS);
					String priceS = product.get("product_price");
					double price = Double.valueOf(priceS).doubleValue() * Integer.valueOf(numS).intValue();
					totalPrice += price;
					product.put("price", String.valueOf(price));
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String sql = "insert into `order`(order_no,order_customer_name,order_customer_mobile,order_customer_qq,order_status,order_create_time)" +
				" values(?,?,?,?,?,?)";
		SQLTool.insert(sql, new Object[]{
				getOrderNo(),
				request.getParameter("scheme_customer_name"),
				request.getParameter("scheme_customer_mobile"),
				request.getParameter("scheme_customer_qq"),
				1,
				new Date()
				});
		sql = "select max(order_id) orderId from `order`";
		List<HashMap<String, String>> list = SQLTool.query(sql);
		if (list != null && list.size() > 0) {
			long orderId = Long.parseLong(list.get(0).get("orderId"));
			for (int i = 0; i < trolleySize; i++) {
				HashMap<String, String> product = trolley.get(i);
				addOrderDetail(orderId, product.get("config_id"), product.get("config_name"), product.get("product_id"), product.get("num"));
			}
		}

		//删除购物车产品
		OpCookies.Del_Cookies("trolleyJSON", "/pc/product/", response);

		//提示
		PrintWriter pw = response.getWriter();
		pw.append("<script type=\"text/javascript\">");
		pw.append("alert(\"购买成功！\");");
		pw.append("window.close();");
		pw.append("</script>");
		pw.flush();

		return null;
	}
	
	/**
	 * 添加配置表的明细
	 */
	private void addOrderDetail(long orderId, String configId, String configName, String productId, String num) {

		try {
			String sql = " select * from product where product_status=1 and product_id=" + productId;
			List<HashMap<String, String>> list2 = SQLTool.query(sql);
			if (list2 == null || list2.size() == 0)
				return;
			HashMap<String, String> product = list2.get(0);
			sql = "insert into order_detail(order_id,config_id,config_name,product_id,product_brand_name,"
					+ "product_name,product_pic_url,product_price,order_detail_product_num) values(?,?,?,?,?,?,?,?,?)";
			SQLTool.insert(
					sql,
					new Object[] {orderId, configId, configName,
							productId, product.get("product_brand_name"),
							product.get("product_name"),
							product.get("product_pic_url"),
							product.get("product_price"), num});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取订单编号
	 * 
	 * @return
	 */
	private String getOrderNo() {

		try {
			String curDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			String resultDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
			String beginTime = curDate + " 00:00:00";
			String endTime = curDate + " 23:59:59";
			String sql = "select (max(order_no) + 1) as orderNo from `order` where order_create_time>='"
					+ beginTime + "' and order_create_time<='" + endTime + "'";
			String schemeNo = "";
			List<HashMap<String, String>> list = SQLTool.query(sql);
			if (list != null && list.size() > 0) {
				schemeNo = list.get(0).get("orderNo");
				if (schemeNo.equals(""))
					schemeNo = resultDate + "0001";
			} else {
				schemeNo = resultDate + "0001";
			}
			return schemeNo;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private JSONObject[] getTrolley(HttpServletRequest request) throws Exception {

		JSONObject[] trolleyJSONObject_Array = null;

		Cookie[] cookies = request.getCookies();
		String cookiesValue = null;
		String cookieName = null;
		Cookie cookie = null;
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				cookie = cookies[i];
				cookieName = cookie.getName();
				if (cookieName.equals("trolleyJSON")) {
					cookiesValue = StringTool.unescape(cookie.getValue());
				}
			}
		}

		if (cookiesValue != null && !"".equals(cookiesValue)) {
			JSONArray trolleyJSONArray = JSONArray.fromObject(cookiesValue);
			Object[] trolleyJSON_ObjectArray = trolleyJSONArray.toArray();
			trolleyJSONObject_Array = new JSONObject[trolleyJSON_ObjectArray.length];
			for (int i = trolleyJSONObject_Array.length - 1; i >= 0; i --) {
				trolleyJSONObject_Array[i] = JSONObject.fromObject(trolleyJSON_ObjectArray[i]);
			}
		}

		return trolleyJSONObject_Array;
	}

	private String getProductIdsS(JSONObject[] trolleyJSONObjectArray) {

		StringBuffer productIdsSB = new StringBuffer();

		for (int i = trolleyJSONObjectArray.length - 1; i >= 0; i --) {
			Integer productId = (Integer) trolleyJSONObjectArray[i].get("product_id");
			productIdsSB.append(productId);
			if (i > 0) {
				productIdsSB.append(",");
			}
		}

		return productIdsSB.toString();
	}
}
